<?php

namespace app\admin\controller;

use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Voucher extends AdminControl
{

    private $quotastate_arr;
    private $templatestate_arr;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/voucher.lang.php');
        if (config('voucher_allow') != 1 || config('points_isuse') != 1) {
            $this->error(lang('admin_voucher_unavailable'), 'operation/setting');
        }
        $this->quotastate_arr = array(
            'activity' => array(1, lang('admin_voucher_quotastate_activity')),
            'cancel' => array(2, lang('admin_voucher_quotastate_cancel')),
            'expire' => array(3, lang('admin_voucher_quotastate_expire'))
        );
        //代金券模板状态
        $this->templatestate_arr = array(
            'usable' => array(1, lang('admin_voucher_templatestate_usable')),
            'disabled' => array(2, lang('admin_voucher_templatestate_disabled'))
        );
        $this->assign('quotastate_arr', $this->quotastate_arr);
        $this->assign('templatestate_arr', $this->templatestate_arr);
    }

    /**
     * 代金券设置
     */
    public function setting()
    {
        $setting_model = model('config');
        if (request()->isPost()) {
            $data = [
                'promotion_voucher_price' => input('post.promotion_voucher_price'),
                'promotion_voucher_storetimes_limit' => input('post.promotion_voucher_storetimes_limit'),
                'promotion_voucher_buyertimes_limit' => input('post.promotion_voucher_buyertimes_limit')
            ];

            $voucher_validate = validate('voucher');
            if (!$voucher_validate->scene('setting')->check($data)) {
                $this->error($voucher_validate->getError());
            }
            //每月代金劵软件服务单价
            $promotion_voucher_price = intval(input('post.promotion_voucher_price'));
            if ($promotion_voucher_price < 0) {
                $this->error(lang('param_error'));
            }
            //每月店铺可以发布的代金劵数量
            $promotion_voucher_storetimes_limit = intval(input('post.promotion_voucher_storetimes_limit'));
            if ($promotion_voucher_storetimes_limit <= 0) {
                $promotion_voucher_storetimes_limit = 20;
            }
            //买家可以领取的代金劵总数
            $promotion_voucher_buyertimes_limit = intval(input('post.promotion_voucher_buyertimes_limit'));
            if ($promotion_voucher_buyertimes_limit <= 0) {
                $promotion_voucher_buyertimes_limit = 5;
            }
            $update_array = array();
            $update_array['promotion_voucher_price'] = $promotion_voucher_price;
            $update_array['voucher_storetimes_limit'] = $promotion_voucher_storetimes_limit;
            $update_array['voucher_buyertimes_limit'] = $promotion_voucher_buyertimes_limit;
            $result = $setting_model->editConfig($update_array);
            if ($result) {
                $this->log(lang('admin_voucher_setting') . lang('ds_voucher_price_manage'));
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->error(lang('ds_common_save_fail'));
            }
        } else {
            $setting = rkcache('config', true);
            $this->assign('setting', $setting);
            return $this->fetch();
        }
    }


    /**
     * Notes:添加优惠券
     * User: shen
     * Date: 2020/5/6
     * Time: 17:25
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function priceadd()
    {
        if (request()->isPost()) {
            $data = input('post.');

            // $name = [];
            // foreach ($data['b_ids'] as $key => $value) {
            //     $b_name = db('brand')->where(['brand_id'=>$value])->find();
            //     $name[] = $b_name['brand_name'];
            // }
            // $b_names = implode(',', $name);
            // $b_ids = json_encode($data['b_ids']);
            /*$b_names = $data['b_name'];
            $b_ids = $data['b_id'];*/


            $new_array = array();
            $new_array['voucher_title'] = $data['title'];
            $new_array['vou_type'] = $data['vou_type'];
            if ($data['vou_type'] == 1) {
                #商城
                $new_array['vou_gcid'] = $data['class_id'];
                if ($data['class_id'] == 0 || $data['class_id'] == '') {
                    $new_array['vou_gcname'] = '通用';
                } else {
                    $new_array['vou_gcname'] = $data['class_name'];
                }
            } elseif ($data['vou_type'] == 2) {
                #服务
                $new_array['vou_gcid'] = $data['vou_type_content'];
                $vou_type_content = array('1' => '保养', '2' => '维修', '3' => '安装', '4' => '拆移');
                $new_array['vou_gcname'] = $vou_type_content[$data['vou_type_content']];
            } else {
                #项目
                $new_array['vou_gcid'] = '';
                $new_array['vou_gcname'] = '通用';
            }
            $new_array['voucher_price'] = $data['voucher_price'];
            $new_array['voucher_limit'] = $data['voucher_limit'];
            $new_array['voucher_startdate'] = strtotime($data['voucher_startdate']);
            $new_array['voucher_enddate'] = strtotime($data['voucher_enddate']);
            $new_array['use_date'] = $data['use_date'];
            $new_array['g_ratio'] = $data['g_ratio'];
            $new_array['y_ratio'] = $data['y_ratio'];
            $new_array['z_ratio'] = $data['z_ratio'];
            $new_array['status'] = $data['status'];
            $new_array['count'] = $data['count'];
            $new_array['surplus_count'] = $data['count'];
            $new_array['score_count'] = $data['score_count'];
            $new_array['add_time'] = time();
            /* $new_array['b_ids'] = $b_ids;
             $new_array['b_names'] = $b_names;*/
            $res = db('voucher')->data($new_array)->insert();
            if ($res) {
                $this->log(lang('ds_add') . lang('admin_voucher_priceadd') . '[' . input('post.voucher_price') . ']');
                return json(['code' => 1, 'url' => url('Voucher/index'), 'msg' => lang('ds_common_save_succ')]);
            } else {
                return json(['code' => 0, 'url' => url('Voucher/index'), 'msg' => '添加失败']);
            }
        } else {
            $type = [
                'class_id' => 0,
            ];
            $this->assign('type', $type);
            $goodsclass_model = model('goodsclass');
            //父类列表，只取到第二级
            $parent_list = $goodsclass_model->getTreeClassList(2);
            $gc_list = array();
            if (is_array($parent_list)) {
                foreach ($parent_list as $k => $v) {
                    $parent_list[$k]['gc_name'] = str_repeat("&nbsp;", $v['deep'] * 2) . $v['gc_name'];
                    if ($v['deep'] == 1)
                        $gc_list[$k] = $v;
                }
            }
            $this->assign('gc_list', $gc_list);

            $brand_list = model('brand')->getBrandPassedList(array());
            $this->assign('brand_list', $brand_list);

            $info = [];
            $this->assign('info', $info);
            $this->setAdminCurItem('priceadd');

            //获取优惠劵赠送模式
            $voucher_type = db('voucher_type')->select();
            $this->assign('voucher_type', $voucher_type);


            return $this->fetch();
        }
    }

    /*
     * 删除代金券面额
     */

    public function drop()
    {
        $id = trim(input('param.id'));
        if (empty($id)) {
            ds_json_encode(10001, '操作失败');
        }
        $data = array();
        $data['is_del'] = 1;
        $data['del_time'] = time();
        $rs = db('voucher')->where('voucher_id', $id)->data($data)->update();
        if ($rs) {
            $this->log(lang('ds_del') . lang('admin_voucher_priceadd') . '[ID:' . $id . ']');
            ds_json_encode(10000, lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_del_fail'));
        }
    }

    /*
     * 上下架
     */

    public function status()
    {
        $id = trim(input('param.id'));
        $status = trim(input('param.status'));
        if (empty($id)) {
            ds_json_encode(10001, '操作失败');
        }
        $info = db('voucher')->where('voucher_id', $id)->find();
        if ($status == $info['status']) {
            ds_json_encode(10001, '操作失败');
        }
        $data = array();
        $data['status'] = $status;
        $rs = db('voucher')->where('voucher_id', $id)->data($data)->update();
        if ($rs) {
            $this->log(lang('ds_del') . lang('admin_voucher_priceadd') . '[ID:' . $id . ']');
            ds_json_encode(10000, '操作成功');
        } else {
            ds_json_encode(10001, '操作失败');
        }
    }

    /**
     * 商品详情页
     */
    public function voucher_setting_info()
    {
        if (request()->isPost()) {
        } else {
            $id = input('param.id');
            $voucher_info = db('voucher')->where(['voucher_id' => $id])->find();
            $this->assign('voucher_info', $voucher_info);
            $vou_type_content = array('1' => '商城', '2' => '服务', '3' => '项目');
            $this->assign('vou_type_content', $vou_type_content);
            return $this->fetch();
        }
    }

    /**
     * 代金券列表
     */
    public function index()
    {
        $param = array();
        if (trim(input('param.store_name'))) {
            $title_name = input('param.store_name');
            $param['voucher_title'] = array('like', "%$title_name%");
        }
        if (trim(input('param.sdate')) && trim(input('param.edate'))) {
            $sdate = strtotime(input('param.sdate'));
            $edate = strtotime(input('param.edate'));
            $param['voucher_enddate'] = array('between', "$sdate,$edate");
        } elseif (trim(input('param.sdate'))) {
            $sdate = strtotime(input('param.sdate'));
            $param['voucher_enddate'] = array('egt', $sdate);
        } elseif (trim(input('param.edate'))) {
            $edate = strtotime(input('param.edate'));
            $param['voucher_enddate'] = array('elt', $edate);
        }
        $state = intval(input('param.state'));
        if ($state) {
            $param['vou_type'] = $state;
        }

        $recommend = intval(input('param.recommend'));
        if ($recommend) {
            if ($recommend == 2) {
                $param['status'] = 0;
            } else {
                $param['status'] = $recommend;
            }

        }
        $param['is_del'] = 0;

        $voucher_model = model('voucher');
        $vouchertemplate_list = $voucher_model->getVouchertemplateList($param, '', '', 10, 'voucher_id desc');
        // p($vouchertemplate_list);die;
        $this->assign('show_page', $voucher_model->page_info->render());

        $this->assign('vouchertemplate_list', $vouchertemplate_list);
        $vou_type_content = array('1' => '商城', '2' => '服务', '3' => '项目');
        $this->assign('vou_type_content', $vou_type_content);
        // 输出自营店铺IDS
        $this->assign('flippedOwnShopIds', array_flip(model('store')->getOwnShopIds()));
        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    /*
     * 代金券模版编辑
     */

    public function priceedit()
    {
        $type = [
            'class_id' => 0,
        ];
        $this->assign('type', $type);
        $goodsclass_model = model('goodsclass');
        //父类列表，只取到第二级
        $parent_list = $goodsclass_model->getTreeClassList(2);
        $gc_list = array();
        if (is_array($parent_list)) {
            foreach ($parent_list as $k => $v) {
                $parent_list[$k]['gc_name'] = str_repeat("&nbsp;", $v['deep'] * 2) . $v['gc_name'];
                if ($v['deep'] == 1)
                    $gc_list[$k] = $v;
            }
        }
        $this->assign('gc_list', $gc_list);
        $t_id = intval(input('param.id'));
        if ($t_id <= 0) {
            $t_id = intval(input('post.id'));
        }
        if ($t_id <= 0) {
            $this->error(lang('param_error'), 'voucher/index');
        }
        //查询模板信息
        $param = array();
        $param['voucher_id'] = $t_id;
        $voucher_model = model('voucher');
        $t_info = db('voucher')->where($param)->find();

        $info = json_decode($t_info['b_ids'], true);
        $this->assign('info', $info);
        if (empty($t_info)) {
            $this->error(lang('param_error'), 'voucher/index');
        }
        if (request()->isPost()) {
            $data = input('post.');

            // $name = [];
            // foreach ($data['b_ids'] as $key => $value) {
            //     $b_name = db('brand')->where(['brand_id'=>$value])->find();
            //     $name[] = $b_name['brand_name'];
            // }
            // $b_names = implode(',', $name);
            // $b_ids = json_encode($data['b_ids']);
            /*  $b_names = $data['b_name'];
              $b_ids = $data['b_id'];*/
            // p($data);die;
            $new_array = array();
            $new_array['voucher_title'] = $data['title'];
            $new_array['vou_type'] = $data['vou_type'];
            if ($data['vou_type'] == 1) {
                #商城
                #判断是否没有编辑分类
                if (isset($data['edit_class_id'])) {
                    #没有编辑
                    $new_array['vou_gcid'] = $t_info['vou_gcid'];
                    $new_array['vou_gcname'] = $t_info['vou_gcname'];
                } else {
                    #编辑了
                    $new_array['vou_gcid'] = $data['class_id'];
                    if ($data['class_id'] == 0 || $data['class_id'] == '') {
                        $new_array['vou_gcname'] = '通用';
                    } else {
                        $new_array['vou_gcname'] = $data['class_name'];
                    }
                }


            } elseif ($data['vou_type'] == 2) {
                #服务
                $new_array['vou_gcid'] = $data['vou_type_content'];
                $vou_type_content = array('1' => '保养', '2' => '维修', '3' => '安装', '4' => '拆移');
                $new_array['vou_gcname'] = $vou_type_content[$data['vou_type_content']];
            } else {
                #项目
                $new_array['vou_gcid'] = '';
                $new_array['vou_gcname'] = '通用';
            }
            $new_array['voucher_price'] = $data['voucher_price'];
            $new_array['voucher_limit'] = $data['voucher_limit'];
            $new_array['voucher_startdate'] = strtotime($data['voucher_startdate']);
            $new_array['voucher_enddate'] = strtotime($data['voucher_enddate']);
            $new_array['use_date'] = $data['use_date'];
            $new_array['g_ratio'] = $data['g_ratio'];
            $new_array['y_ratio'] = $data['y_ratio'];
            $new_array['z_ratio'] = $data['z_ratio'];
            $new_array['count'] = $data['count'];
            $new_array['surplus_count'] = $data['count'];
            $new_array['score_count'] = $data['score_count'];
            $new_array['status'] = $data['status'];
            /* $new_array['b_ids'] = $b_ids;
             $new_array['b_names'] = $b_names;*/
            $res = db('voucher')->where('voucher_id', $data['id'])->data($new_array)->update();
            if ($res) {
                $this->log('编辑' . '[' . $data['id'] . ']');
                return json(['code' => 1, 'url' => url('Voucher/index'), 'msg' => '编辑成功']);
            } else {
                return json(['code' => 0, 'url' => url('Voucher/index'), 'msg' => '编辑失败']);
            }
        } else {
            $brand_list = model('brand')->getBrandPassedList(array());
            $this->assign('brand_list', $brand_list);
            $this->assign('t_info', $t_info);
            $this->setAdminCurItem('templateedit');
            return $this->fetch('priceadd');
        }
    }


    /**
     * 页面内导航菜单
     * @param string $menu_key 当前导航的menu_key
     * @param array $array 附加菜单
     * @return
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => '优惠券列表',
                'url' => url('Voucher/index')
            ),
            array(
                'name' => 'priceadd',
                'text' => '添加优惠券',
                'url' => url('Voucher/priceadd'))
        );
        return $menu_array;
    }

}
